<template>
    <div>
      <!-- 首页信息 -->
      <van-nav-bar v-if="home === 'home'" class="home-bar">
        <template #left>
          <van-icon name="fire-o" color="#ee0a24" class="cate-bar" />
        </template>
        <template #title>
          <van-search @click="$router.push('/search')" autocomplete="off" class="search" background="#50bb78" shape="round" placeholder="请输入关键字"></van-search>
        </template>
        <template #right>
          <span class="right-bar" @click="$router.push('/login')">{{ a ? '欢迎' : '登录' }}</span>
        </template>
      </van-nav-bar>
      
      <!-- 其它 -->
      <van-nav-bar v-else @click-left="$router.back()" :title="title" left-arrow>
        <template v-if="center === 'search'" #title>
          <van-search  :autofocus="true" 
          v-model="searchText"
          @click="$router.push('/search')" 
          @search="searchHandler"
          @update:model-value="inputHandler"
          autocomplete="off" 
          class="search" 
          placeholder="请输入关键字">
        </van-search>
        </template>
        <template v-if="right === 'search'" #right>
          <van-button type="primary" size="small" @click="searchHandler">搜索</van-button>
        </template>

        <template v-if="right === 'more'" #right>
          ...
        </template>
      </van-nav-bar>
    </div>
</template>

<script lang="ts" name="sdyFooter" setup>
import {useRouter} from 'vue-router'
const $router = useRouter()
import { ref } from 'vue'

const a = ref(window.localStorage.getItem('token'))

// 定义接收参数的接口
interface HeaderInfo{
  right?:string
  center?:string
  title?:string
  home?:string
}

// 定义自定义事件的接口
interface EmitsInfo {
  (e: 'searchText', str: string): void
}

const emits = defineEmits<EmitsInfo>()
const searchText = ref<string>('')

const searchHandler = () => {
  // 按下回车按钮, 带着当前搜索的关键字
  // 条件判断
  
  if (!searchText.value.trim()) return
  // 把当前搜索关键字存储到 localStorage 内
  // 说明: id 使用一个 随机数字
  const info = {
    wordid: Math.random().toString().slice(-8),
    keyword: searchText.value
  }

  // 拿到 localStorage 内的内容, 把 info 加进去
  // 再把加号 info 的内容从新存储
  console.log(321);
  
  const searchList = JSON.parse(window.localStorage.getItem('searchList') || '[]')
  searchList.unshift(info)
  window.localStorage.setItem('searchList', JSON.stringify(searchList))

  // 并且跳转路由到 /list 组件
  $router.replace({ path: '/list', query: { keyword: info.keyword } })
}

defineProps<HeaderInfo>()
// 当我们输入内容的时候, 实时把内容传递给父组件
const inputHandler = () => {
  // 触发自己的自定义事件
  emits('searchText', searchText.value)
}
</script>

<style lang="scss" scoped>
.search{
  width: 100%;
  padding-left: 0;
  font-size:12px;
}
.home-bar{
  background-color: #50bb78;
}
.cate-bar{
  font-size: 20px;
}
.right-bar{
  background-color: #50bb78;
}
</style>